package MTClient;

import java.awt.*;
import java.io.*;
import java.net.*;

import android.util.Log;

import MTRequest.MTRequestDataSource;

public class ClientTCPConnection implements Runnable, MTRequestDataSource
{
	// The socket connecting us to the server
	private static ClientTCPConnection mClientTCPConnection = null;
	
	private Socket socket;
	
	private MessageCentre aMSGCenter;

	public static ClientTCPConnection GetInstance()
	{
		if( null == mClientTCPConnection ){
			mClientTCPConnection = new ClientTCPConnection();
		}
		return mClientTCPConnection;
	}
	
	// Constructor
	public ClientTCPConnection() 
	{
		
		// Connect to the server
		try {
			// Initiate the connection
			Log.e("Money", InetAddress.getLocalHost().toString() );

			if( MTConstant.MT_TCP_IS_LOCALHOST ){
				socket = new Socket( InetAddress.getByAddress( MTConstant.MT_TCP_LOCAL_ADDRESS ), MTConstant.MT_PORT );
			}
			else{
				socket = new Socket( InetAddress.getByAddress( MTConstant.MT_TCP_SERVER_ADDRESS ), MTConstant.MT_PORT );
			}
				// We got a connection! Tell the world
			System.out.println( "connected to "+socket );
			// Let's grab the streams and create DataInput/Output streams
			// from them
			
			// set timeout for read calls
			socket.setSoTimeout(15000);

			// Start a background thread for receiving messages
			
			aMSGCenter = new MessageCentre( 
					new DataInputStream( socket.getInputStream() ),
					new DataOutputStream( socket.getOutputStream() ) );
			
			new Thread( this ).start();
		} 
		catch( IOException ie ){ 
			System.out.println( ie ); 
		}
		System.out.println( "TCP Connect!" );
	}
	
	// Background thread runs this: show messages from other window
	public void run() 
	{
		try {
			// Receive messages
			aMSGCenter.ReceiveMSG();
		} 
		catch( IOException ie ){ 
			System.out.println( ie ); 
			
			// timeout, close socket
			try {
				socket.close();
			} catch (IOException e) {
				System.out.println( ie ); 
			}
			mClientTCPConnection = null;
			System.out.println("socket closed due to inactivity/timeout");
			
			
		}
	}
	
	public MessageCentre GetMSGCenter()
	{
		return aMSGCenter;
	}
	
	public String GetRawData()
	{
		return "";
	}
	
	public void Notify( int RequestID, int RequestState, String aRawData )
	{
		System.out.println("----> void Notify( boolean aChanged )");
		//System.out.println("aChanged:" + aChanged );
		System.out.println("<---- void Notify( boolean aChanged )");
	}
	
	public void SendRequest( int aRequestID, MTRequestDataSource aDataSource )
	{
		aMSGCenter.SendRequest( aRequestID, aDataSource );
	}


}
